import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:html/parser.dart';
import 'package:wu_you/data/repository/mall_repository.dart';
import 'package:wu_you/l10n/messages.dart';
import 'package:wu_you/model/mall/mall_model.dart';
import 'package:wu_you/page/mall/page_product_exc_preview.dart';
import 'package:wu_you/res/colors.dart';
import 'package:wu_you/state/bloc/http_bloc.dart';
import 'package:wu_you/state/bloc/mall_bloc.dart';
import 'package:wu_you/state/cubit/basic_cubit.dart';
import 'package:wu_you/utils/error_handler.dart';
import 'package:wu_you/utils/navigator_util.dart';
import 'package:wu_you/utils/utils.dart';
import 'package:wu_you/widgets/appbar_leading.dart';
import 'package:wu_you/widgets/html/flutter_html.dart';
import 'package:wu_you/widgets/html/html_parser.dart';
import 'package:wu_you/widgets/html/style.dart';
import 'package:wu_you/widgets/http_status_button.dart';
import 'package:wu_you/widgets/http_status_widget.dart';
import 'package:wu_you/widgets/number_choose_widget.dart';
import 'package:wu_you/widgets/page_dialog_pop.dart';
import 'package:toast/toast.dart';
import 'package:wu_you/utils/extension_utils.dart';


/// 商品详情
class ExcProductDetailInfo extends StatefulWidget{
  final String productId;
  ExcProductDetailInfo({Key key,this.productId}):super(key: key);
  @override
  ExcProductDetailInfoState createState() => ExcProductDetailInfoState();
}
class ExcProductDetailInfoState extends State<ExcProductDetailInfo>{
  IntCubit _cubit = IntCubit(value: 1);
  SwiperController _controller = SwiperController();
  int _number = 1;
  GoodsDetail _model;
  ProductSkuNewModel _oneSpec;
  NewProductSkuModel _productSkuModel;

  var message;
  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    double width = MediaQuery.of(context).size.width;
    return HttpWidget<GoodsDetail, NewProductDetailBloc>(
      create: (context) => NewProductDetailBloc()..add(IdHttpEvent(int.parse(widget.productId))),
      child: (context, data) {
        _model = data;
        List<ProductImage> imageList = data.imgs;
        if(imageList.length == 0){
          imageList.add(ProductImage(file_url: data.img_url));
        }
        if (data.spec.length == 1 && data.spec.first.children.length == 1) {
          _oneSpec = data.spec.first;
          if(getSku == false){
            _loadSku();
          }
        }
        return Scaffold(
          backgroundColor: Colors.white,
          body: NestedScrollView(
            headerSliverBuilder: (context, innerBoxIsScrolled) {
              return [
                BlocProvider(
                    create: (context) => _cubit,
                    child: BlocBuilder<IntCubit, int>(
                        builder: (BuildContext context, int selIndex) {
                          return SliverAppBar(
                          pinned: true,
                          primary: true,
                          toolbarHeight: 56,
                          elevation: 0,
                          expandedHeight: width / 1.1,
                          backgroundColor: AppColors.primaryColor,
                          leading:
                          AppBarLeading.leading("ic_mall_black_back"),
                          flexibleSpace: FlexibleSpaceBar(
                              stretchModes: <StretchMode>[
                                StretchMode.fadeTitle,
                                StretchMode.zoomBackground
                              ],
                              background: Stack(
                                children: [
                                  Swiper(
                                    itemBuilder: (context, index) {
                                      return Image.network(
                                        "${imageList[index].file_url}",
                                        fit: BoxFit.fill,
                                      );
                                    },
                                    itemCount: imageList.length,
                                    onIndexChanged: (index) {
                                      _cubit.value = index + 1;
                                    },
                                    controller: _controller,
                                    pagination: SwiperPagination(
                                      margin: EdgeInsets.all(5.0),
                                      builder: DotSwiperPaginationBuilder(
                                          size: 3, activeSize: 5),
                                    ),
                                  ),
                                  Positioned(
                                    right: 14,
                                    bottom: 14,
                                    width: 40,
                                    height: 24,
                                    child: Container(
                                      decoration: BoxDecoration(
                                          borderRadius:
                                          BorderRadius.circular(12),
                                          color: AppColors.primaryColor
                                              .withOpacity(0.43)),
                                      alignment: Alignment.center,
                                      child: Text(
                                        "${selIndex}/${imageList.length}",
                                        style: TextStyle(
                                            color: Colors.white,
                                            fontSize: 12),
                                      ),
                                    ),
                                  ),
                                ],
                              )),
                        );
                    }
                  )
                ),
              ];
            },
            body: ListView(
              padding: EdgeInsets.zero,
              children: [
                Container(
                  width: double.infinity,
                  height: 50,
                  padding: EdgeInsets.only(right: 12),
                  decoration: BoxDecoration(
                      gradient: LinearGradient(colors: [
                        AppColors.primaryColor,
                        AppColors.secondColor
                      ])),
                  child: Container(
                    padding: EdgeInsets.only(left: 15),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        RichText(
                            text: TextSpan(children: [
                              TextSpan(
                                  text: "无忧积分:",
                                  style: TextStyle(
                                      color: Colors.white, fontSize: 14)),
                              TextSpan(
                                // text: "${info.productSalePrice}",
                                  text: "${data.sell_price}",
                                  style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 22,
                                      fontWeight: FontWeight.bold))
                            ])),
                        Text(
                          "${message['product1']}￥:${data.old_price}",
                          style: TextStyle(
                              decoration:
                              TextDecoration.lineThrough,
                              color: Colors.white),
                        )
                      ],
                    ),
                  ),
                ),
                Container(
                  color: Colors.white,
                  padding: EdgeInsets.only(left: 15),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Padding(
                        padding: EdgeInsets.only(top: 5),
                        child: Text("${data.name}", style: TextStyle(fontSize: 18, color: AppColors.textColor,fontWeight: FontWeight.bold)),
                      ),
                      Padding(
                        padding: EdgeInsets.only(bottom: 5),
                        child: Text("${data.title}", style: TextStyle(fontSize: 15, color: AppColors.textColor)),
                      ),
                    ],
                  ),
                ),
                Column(
                  children: [
                    // Container(
                    //   height: 40,
                    //   alignment: Alignment.centerLeft,
                    //   padding: EdgeInsets.only(left: 15),
                    //   child: Text("${message['product2']}:${data.stock}  ${message['product3']}:${data.sales_volume}", style: TextStyle(fontSize: 12, color: AppColors.textHintColor)),
                    // ),
                    _addSpaceItem(
                        ListTile(
                            contentPadding: EdgeInsets.all(0),
                            dense: true,
                            visualDensity: VisualDensity(vertical: -2),
                            leading: Text("${message['product4']}", style: TextStyle(fontSize: 13, color: AppColors.textSecondaryColor),),
                            title: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Text("${data.sell_price}", style: TextStyle(fontSize: 13,color: AppColors.textColor,)),
                                SizedBox(width: 5,),
                                // Offstage(
                                //     offstage: (double.parse("${data.fees}") > 0) ? false : true,
                                //     child: Image.asset(Utils.getImgPath("ic_forget_password"),width: 15,color: AppColors.accentColor,)
                                // ).addGesture(() {
                                //   ShowTipsDialog.show(
                                //       context,
                                //       "购买须知",
                                //       "交易手续费：所需金豆${data.fees}",
                                //       "ic_product_tips");
                                // })
                              ],
                            ),
                        ), false),
                    ///购买数量
                    _addSpaceItem(
                        ListTile(
                          dense: true,
                          contentPadding: EdgeInsets.all(0),
                          visualDensity: VisualDensity(vertical: 0),
                          leading: Text(
                            "${message['product5']}",
                            style: TextStyle(
                                fontSize: 13,
                                color: AppColors.textSecondaryColor),
                          ),
                          trailing: NumberChooseWidget(
                            initValue: _number,
                            min: 1,
                            max: int.parse("${data.stock}"),
                            onChange: (value) {
                              _number = value;
                            },
                          ),
                        ),
                        _oneSpec == null),
                    // 兑换须知
                    _addSpaceItem(
                        ListTile(
                            onTap: () {
                            },
                            dense: true,
                            contentPadding: EdgeInsets.all(0),
                            visualDensity: VisualDensity(vertical: -2),
                            leading: Text(
                              "购买须知",
                              style: TextStyle(
                                  fontSize: 13,
                                  color: AppColors.textSecondaryColor),
                            ),
                            title: Padding(
                              padding: EdgeInsets.only(right: 12),
                              child: Text(
                                "购买商品须知...",
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    color: AppColors.textColor),
                              ),
                            )),
                        true),
                  ],
                ),

                Html(
                  data: parse(data.content).outerHtml,
                  style: {
                    "html": Style(
                      backgroundColor: Colors.white,
                    ),
                    "table": Style(
                      backgroundColor:
                      Color.fromARGB(0x50, 0xee, 0xee, 0xee),
                    ),
                    "tr": Style(
                      border:
                      Border(bottom: BorderSide(color: Colors.grey)),
                    ),
                    "th": Style(
                      backgroundColor: Colors.grey,
                    ),
                    "td": Style(
                      alignment: Alignment.topLeft,
                    ),
                    "var": Style(fontFamily: 'serif'),
                    "p": Style(
                      margin: EdgeInsets.all(0),
                      padding: EdgeInsets.all(0),
                    ),
                  },
                  customRender: {
                    "flutter": (RenderContext context, Widget child,
                        attributes, _) {
                      return FlutterLogo(
                        style: (attributes['horizontal'] != null)
                            ? FlutterLogoStyle.horizontal
                            : FlutterLogoStyle.markOnly,
                        textColor: context.style.color,
                        size: context.style.fontSize.size * 5,
                      );
                    },
                  },
                ),
              ],
            ),
          ),
          bottomNavigationBar:SafeArea(
            top: false,
            bottom: true,
            left: false,
            right: false,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 0),
              height: 50,
              width: double.infinity,
              child: GestureDetector(
                onTap: (){
                  if (_oneSpec != null && getSku) {
                    NavigatorUtil.navigateToPage(context, ExcProductPreViewPage(productSkuModel: _productSkuModel, model: _model,number: _number,));
                    return;
                  }
                  ///选择规格
                  showModalBottomSheet(
                    context: context,
                    isScrollControlled: true,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.vertical(
                          top: Radius.circular(16)),
                    ),
                    builder: (context) {
                      return _ProductSpecSelectView(model: data);
                    },
                  );
                },
                child: Container(
                  height: double.infinity,
                  alignment: Alignment.center,
                  child: Text(
                    '${message['product6']}',
                    style: TextStyle(color: Colors.white),
                  ),
                  color: AppColors.primaryColor,
                ),
              )
            ),
          )
        );
      }
    );
  }
  Widget _addSpaceItem(Widget child, bool hidden) {
    Widget result = Offstage(
        offstage: hidden,
        child: Container(
          width: double.infinity,
          color: Colors.transparent,
          child: Column(
            children: [
              Padding(
                padding: EdgeInsets.only(left: 15, bottom: 5),
                child: child,
              ),
              Divider(
                thickness: 5,
                color: HexColor("#EFEDED"),
              ),
            ],
          ),
        ));
    return result;
  }

  bool getSku = false;
  void _loadSku() {
    Map<String, int> defaultSpec = {
      _oneSpec.spec_id.toString(): int.parse("${_oneSpec.children.first.spec_id}"),
    };
    MallRepository.getNewProductSkuDetail(_model.goods_id, defaultSpec).then((value) {
      this._productSkuModel = value;
      getSku = true;
    }).catchError((error) {
      ErrorHandler.handleError(error, action: (msg) {
        Toast.show(msg, context);
      });
    });
  }
}

class _ProductSpecSelectView extends StatefulWidget {
  final GoodsDetail model;
  _ProductSpecSelectView({
    Key key,
    @required this.model,
  })  : assert(model != null),
        super(key: key);
  @override
  _ProductSpecSelectViewState createState() => _ProductSpecSelectViewState();
}

class _ProductSpecSelectViewState extends State<_ProductSpecSelectView> {
  final Map<String, dynamic> _selectedSpec = {};
  ButtonStatusController _controller;
  bool _isPress = true;
  int _number = 1;
  NewProductSkuModel _productSkuModel;

  String _skuPrice(){
    return "${_productSkuModel != null ? _productSkuModel.sku_linglong_price : widget.model.sell_price}";;
  }

  var message;
  @override
  Widget build(BuildContext context) {
    GoodsDetail model = widget.model;
    message = AppLocalizations.of(context);
    return FractionallySizedBox(
      heightFactor: 0.75,
      child: Column(
        children: [
          Stack(
            alignment: Alignment.center,
            children: [
              Padding(
                padding: EdgeInsets.all(32),
                child: IntrinsicHeight(
                  child: Row(
                    children: [
                      GestureDetector(
                        onTap: () {
                        },
                        child: ClipRRect(
                            borderRadius: BorderRadius.circular(5),
                            child: Image.network(
                              (_productSkuModel != null&&_productSkuModel.sku_img_url!="")
                                  ? _productSkuModel.sku_img_url
                                  : model.img_url,
                              width: 80,
                              height: 80,
                              fit: BoxFit.fill,
                            )),
                      ),
                      VerticalDivider(width: 8, color: Colors.transparent),
                      Expanded(
                        child: Column(
                          mainAxisSize: MainAxisSize.max,
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              _skuPrice(),
                              style: TextStyle(
                                  fontSize: 14, color: AppColors.primaryColor),
                            ),
                            Text(
                              "${message['product2']}: ${_productSkuModel != null ? _productSkuModel.sku_stock : model.stock}",
                              style: TextStyle(
                                  fontSize: 14, color: AppColors.textHintColor),
                            ),
                            Text(
                              "${_productSkuModel != null ? "${message['product33']}:" + _productSkuModel.spec_name : "${message['product34']}"}",
                              style: TextStyle(
                                  fontSize: 14, color: AppColors.textColor),
                            ),
                          ],
                        ),
                      )
                    ],
                  ),
                ),
              ),
              Positioned(
                right: 0,
                top: 0,
                child: CloseButton(),
              ),
            ],
          ),
          Padding(
            padding: EdgeInsets.symmetric(vertical: 8),
            child: Divider(),
          ),
          Expanded(
            child: ListView.separated(
              padding: EdgeInsets.all(16),
              shrinkWrap: true,
              itemCount: model.spec.length + 1,
              separatorBuilder: (context, index) {
                return Padding(
                  padding: EdgeInsets.symmetric(vertical: 8),
                  child: Divider(),
                );
              },
              itemBuilder: (context, index) {
                if (index == model.spec.length) {
                  return ListTile(
                    contentPadding: EdgeInsets.zero,
                    leading: Text(
                      "${message['product5']}",
                      style:
                      TextStyle(fontSize: 16, color: AppColors.textColor),
                    ),
                    trailing: NumberChooseWidget(
                      initValue: _number,
                      min: 1,
                      max: int.parse("${model.stock}"),
                      onChange: (value) {
                        _number = value;
                        setState(() {});
                      },
                    ),
                  );
                }
                ProductSkuNewModel skuModel = model.spec[index];
                return _SpecView(
                  model: skuModel,
                  onSelected: (id, detailId) {
                    _selectedSpec[id.toString()] = detailId;
                    if (_selectedSpec.length == model.spec.length) {
                      _isPress = false;
                      _controller.value = ButtonStatus.loading;
                    }
                  },
                );
              },
            ),
          ),
          SafeArea(
            top: false,
            bottom: true,
            left: false,
            right: false,
            minimum: EdgeInsets.only(bottom: 4),
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 16),
              child: StatusButton(
                none: Text(
                  "${message['product6']}",
                  style: TextStyle(color: Colors.white),
                ),
                stateController: (controller) {
                  _controller = controller;
                  _controller.listen((state) {
                    switch (state) {
                      case ButtonStatus.none:
                        break;
                      case ButtonStatus.loading:
                        if (_isPress) {
                          _buy();
                        } else {
                          _loadSku();
                        }
                        break;
                      case ButtonStatus.done:
                        break;
                    }
                  });
                },
                onPressed: () {
                  if (_controller.state != ButtonStatus.none) {
                    return;
                  }
                  if (_productSkuModel == null) {
                    Toast.show("${message['product34']}", context);
                    return;
                  }
                  if (_number > int.parse("${model.stock}")) {
                    Toast.show("${message['product35']}", context);
                    return;
                  }
                  _controller.value = ButtonStatus.loading;
                },
                done: Text("${message['Success']}"),
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _loadSku() {
    MallRepository.getNewProductSkuDetail(widget.model.goods_id, _selectedSpec).then((value) {
      if(value == null){
        Toast.show("${message['trad57']}", context);
        return;
      }
      setState(() {
        this._productSkuModel = value;
      });
    }).catchError((error) {
      ErrorHandler.handleError(error, action: (msg) {
        Toast.show(msg, context);
      });
    }).whenComplete(() {
      _isPress = true;
      _controller.value = ButtonStatus.none;
    });
  }

  void _buy() {
    NavigatorUtil.navigateToPage(context, ExcProductPreViewPage(productSkuModel: _productSkuModel,model: widget.model,number: _number,)).then((value) {
      value == null
          ? _controller.value = ButtonStatus.none
          : _controller.value = ButtonStatus.done;
    }).catchError((error) {
      _controller.value = ButtonStatus.none;
    });
  }
}
class _SpecView extends StatefulWidget {
  final ProductSkuNewModel model;
  final Function(dynamic, dynamic) onSelected;

  _SpecView({
    Key key,
    @required this.model,
    @required this.onSelected,
  })  : assert(model != null),
        assert(onSelected != null),
        super(key: key);

  @override
  _SpecViewState createState() => _SpecViewState();
}

class _SpecViewState extends State<_SpecView> {
  String _selectId = "0";

  @override
  Widget build(BuildContext context) {
    ProductSkuNewModel model = widget.model;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          "${model.name}",
          style: TextStyle(fontSize: 16, color: AppColors.textColor),
        ),
        Wrap(
          spacing: 12,
          children: model.children.map((e) {
            return ChoiceChip(
              elevation: 0,
              padding: EdgeInsets.symmetric(horizontal: 4),
              label: Text('${e.name}',
                  style: TextStyle(
                      color: _selectId == e.spec_id
                          ? Colors.white
                          : AppColors.textColor)),
              selected: _selectId == e.spec_id,
              selectedColor: AppColors.primaryColor,
              backgroundColor: HexColor("#EFEDED"),
              onSelected: (v) {
                if (_selectId == e.spec_id) {
                  return;
                }
                setState(() {
                  _selectId = e.spec_id;
                });
                widget.onSelected(model.spec_id, e.spec_id);
              },
            );
          }).toList(),
        ),
      ],
    );
  }
}
